package cn.mysource.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginCheckFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";  //指定过滤器类型
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String uri = request.getRequestURI();
        //如果uri是以login或者register结尾就返回false
        if(uri.endsWith("login") || uri.endsWith("register")){

            return false;
        }

        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        //从对应的过滤器那里c过来  获取到请求头的token
        RequestContext context = RequestContext.getCurrentContext();
        String token = context.getRequest().getHeader("token");

        if(StringUtils.isEmpty(token)){
            HttpServletResponse response = context.getResponse();
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            Map<String,Object> map = new HashMap<>();
            map.put("message","请你进行登录！");
            map.put("success",false);
            map.put("obj","noLogin");
            String jsonStr = JSON.toJSONString(map);
            writer.write(jsonStr);
            RequestContext.getCurrentContext().setSendZuulResponse(false);
            writer.close();
        }

        return true;
    }
}
